package com.cgsd.heyu.down;


import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import androidx.annotation.NonNull;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Description :
 * @author  : xiaoxing
 * 时间：2019/12/13 09
 * 邮箱：only_dream136@sina.com
 */
public class DownLoadUtil {
    private final int WHAT_FAIL = 100;
    private final int WHAT_SUCCESS = 200;
    private final int WHAT_PROGRESS = 300;
    private DownLoadListener listener;
    private  OkHttpClient okHttpClient;
    private String filePath;

    private Handler handler = new Handler(Looper.getMainLooper()){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case WHAT_FAIL:
                    if (listener != null){
                        listener.onFailed();
                    }
                    break;
                case WHAT_SUCCESS:
                    if (listener != null){
                        listener.onSuccess(filePath);
                    }
                    break;
                case WHAT_PROGRESS:
                    Bundle data = msg.getData();
                    long totalSize = data.getLong("totalSize");
                    long currentSize = data.getLong("currentSize");
                    if (listener != null){
                        listener.onProgress(totalSize,currentSize);
                    }
                    break;
                default:
            }
        }
    };
    private ExecutorService service;

    public DownLoadUtil(DownLoadListener listener) {
        this.listener = listener;
        okHttpClient = new OkHttpClient();
    }

    /**
     * 获取http连接处理类HttpURLConnection
     */
    private HttpURLConnection getConnection(String strUrl) {
        URL url;
        HttpURLConnection connection = null;
        try {
            url = new URL(strUrl);
            connection = (HttpURLConnection) url.openConnection();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return connection;
    }

    /**
     * @param url 下载连接
     * @param filePath 下载文件保存路劲
     */

    public void download(String url,  String filePath) {
        this.filePath = filePath;
        service = new ThreadPoolExecutor(1,5,
                1L, TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(3),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy());;
        service.submit(new Runnable() {
            @Override
            public void run() {
                Request request = new Request.Builder()
                        .url(url)
                        .build();
                OkHttpClient client = new OkHttpClient();
                try {
                    Response response = client.newCall(request).execute();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                //异步请求
                okHttpClient.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        // 下载失败监听回调
                        handler.sendEmptyMessage(WHAT_FAIL);
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        InputStream is = null;
                        byte[] buf = new byte[1024*10];
                        int len;
                        FileOutputStream fos = null;
                        try {
                            is = response.body().byteStream();
                            long total = response.body().contentLength();
                            fos = new FileOutputStream(filePath);
                            long sum = 0;
                            while ((len = is.read(buf)) != -1) {
                                fos.write(buf, 0, len);
                                sum += len;
                                int progress = (int) (sum * 1.0f / total * 100);
                                //下载中更新进度条
                                Message message = new Message();
                                message.what = WHAT_PROGRESS;
                                Bundle bundle = new Bundle();
                                bundle.putLong("totalSize",total);
                                bundle.putLong("currentSize",sum);
                                message.setData(bundle);
                                handler.sendMessage(message);
                            }
                            fos.flush();
                            //下载完成
                            handler.removeMessages(WHAT_PROGRESS);
                            handler.sendEmptyMessage(WHAT_SUCCESS);
                        } catch (Exception e) {
                            handler.sendEmptyMessage(WHAT_FAIL);
                        }finally {
                            try {
                                if (is != null) {
                                    is.close();
                                }
                                if (fos != null) {
                                    fos.close();
                                }
                            } catch (IOException e) {

                            }

                        }


                    }
                });
            }
        });
    }

    private void cancel(){
        service.isShutdown();
    }
}
